package soccerBet.project.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import soccerBet.project.contracts.EquipaContract;
import soccerBet.project.objects.Equipa;
import soccerBet.project.objects.Jogo;
import soccerBet.project.utils.HibernateUtil;



public class EquipasDAO {
	
	
	    
		public Equipa getEquipa(Integer equipaId) {
	
			Session session = HibernateUtil.getSessionFactory().openSession();
			
			Equipa equipa = (Equipa)  session.
			createQuery("select e from Equipa as e where e.idEquipa = ?").setInteger(0, equipaId).uniqueResult();
			
			
			session.close();
			
			return equipa;
	
	
		}
	
	    
		public  void insertALLToDB(List<EquipaContract> equipas) {
			// TODO Auto-generated method stub

				Session session = HibernateUtil.getSessionFactory().openSession();
		        session.beginTransaction();
		        
		        for(EquipaContract eq : equipas){
		        	Equipa e = new Equipa();
		        	e.setIdEquipa(eq.getIdEquipa());
		        	e.setNome(eq.getNomeEquipa());
		        	session.save(e);
		        }
		     
		 
		        //Commit the transaction
		        session.getTransaction().commit();
		      
		    	
				session.close();
			
		}

		public void insertToDB(EquipaContract equipa) {
			// TODO Auto-generated method stub
			
	        
	        

	        if( getEquipa(equipa.getIdEquipa())==null){
	        

				Session session = HibernateUtil.getSessionFactory().openSession();
		        session.beginTransaction();
	        	
	        	Equipa e = new Equipa();
	        	e.setIdEquipa(equipa.getIdEquipa());
	        	e.setNome(equipa.getNomeEquipa());
	        	e.setFavorita(0);
	        	session.saveOrUpdate(e);
	        	
	        	  //Commit the transaction
		        session.getTransaction().commit();
		        
		    	
				session.close();
	        	
	        }

	      
	        
	       
		}
		
	    public List<EquipaContract> getAllEquipas(){
	        
	    	List<EquipaContract> equList = new ArrayList<EquipaContract>();
	    	
			Session session = HibernateUtil.getSessionFactory().openSession();
	    	
	        Query qry = session .createQuery(
	                "from Equipa as eq");
	        
	        List<Equipa> lista = (List<Equipa>)qry.list();
	        
	        for (Equipa u: lista){
	            
	        	equList.add(new EquipaContract(u.getNome(), u.getIdEquipa()));
	        	            
	        }        
	        
	    	
			session.close();
	        
	        return equList;        
	        
	    }



		
	    
	}